import {
  Message,
  MessageBox
} from 'element-ui'
import util from '@/libs/util.js'
import router from '@/router'
import api from '@/api'
import {
  post
} from '@/utils/request'
import {
  adminLoginUrl
} from '@/utils/interface'

export default {
  namespaced: true,
  actions: {
    async login({
      dispatch
    }, {
      username = '',
      password = ''
    } = {}) {
      try {
        const res = await post(adminLoginUrl, {
          username,
          password
        })
        const uuid = res.data.data.uuid
        const token = res.data.data.access
        const moduleauths = res.data.data.moduleauths
        const userinfo = res.data.data
        const isStaff = res.data.data.is_staff // 判断用户是否为staff
        if (isStaff) {
          util.cookies.set('uuid', uuid)
          util.cookies.set('token', token)
          util.cookies.set('moduleauths', moduleauths)
          await dispatch('d2admin/user/set', {
            userinfo: userinfo,
          }, {
            root: true
          })
          await dispatch('load')
        } else {
          throw new Error('不是管理员，登录失败') // 抛出错误
        }
      } catch (error) {
        console.log('登录失败', error)
        Message.error('不是管理员，登录失败')
      }
    },
    logout({
      commit,
      dispatch
    }, {
      confirm = false
    } = {}) {
      async function logout() {
        util.cookies.remove('token')
        util.cookies.remove('uuid')
        util.cookies.remove('moduleauths')
        await dispatch('d2admin/user/set', {}, {
          root: true
        })
        router.push({
          name: 'login'
        })
      }
      if (confirm) {
        commit('d2admin/gray/set', true, {
          root: true
        })
        MessageBox.confirm('确定要注销当前用户吗', '注销用户', {
            type: 'warning'
          })
          .then(() => {
            commit('d2admin/gray/set', false, {
              root: true
            })
            logout()
          })
          .catch(() => {
            commit('d2admin/gray/set', false, {
              root: true
            })
            Message({
              message: '取消注销操作'
            })
          })
      } else {
        logout()
      }
    },
    async load({
      dispatch
    }) {

      await dispatch('d2admin/user/load', null, {
        root: true
      })
      // 加载主题
      await dispatch('d2admin/theme/load', null, {
        root: true
      })
      // 加载页面过渡效果设置
      await dispatch('d2admin/transition/load', null, {
        root: true
      })
      // 持久化数据加载上次退出时的多页列表
      await dispatch('d2admin/page/openedLoad', null, {
        root: true
      })
      // 持久化数据加载侧边栏配置
      await dispatch('d2admin/menu/asideLoad', null, {
        root: true
      })
      // 持久化数据加载全局尺寸
      await dispatch('d2admin/size/load', null, {
        root: true
      })
      // 持久化数据加载颜色设置
      await dispatch('d2admin/color/load', null, {
        root: true
      })
    }
  }
}
